package weiyao.xinxidasai.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weiyao.xinxidasai.DTO.FileItemDTO;
import weiyao.xinxidasai.DTO.FileTreeNode;
import weiyao.xinxidasai.DTO.FolderDetailDTO;
import weiyao.xinxidasai.DTO.Result;
import weiyao.xinxidasai.Utils.ThreadLocal.UserHolder;
import weiyao.xinxidasai.mapper.FilesMapper;
import weiyao.xinxidasai.mapper.FolderMapper;
import weiyao.xinxidasai.mapper.VersionMapper;
import weiyao.xinxidasai.pojo.FFiles;
import weiyao.xinxidasai.pojo.FilesFolder;
import weiyao.xinxidasai.pojo.Version;
import weiyao.xinxidasai.service.FolderService;

import java.util.ArrayList;
import java.util.List;

@Service
public class FolderServiceImpl implements FolderService {
    @Autowired
    private VersionMapper versionMapper;

    @Autowired
    private FolderMapper folderMapper;
@Autowired
private FilesMapper filesMapper;

@Override
@Transactional
    public Result createFolder(String Path) {
    //判断是否有该文件夹
    FilesFolder filesFolder = folderMapper.selectByPathanduser(UserHolder.getUser().getUserId(), Path);
if (filesFolder != null) {
    return Result.fail("文件夹已经被创建 ");
}

        // 2. 创建文件夹记录
        FilesFolder folder = new FilesFolder();
        folder.setUserId(UserHolder.getUser().getUserId());
        folder.setFolderPath(Path);

        folderMapper.insertFolder(folder);
        return Result.ok();
    }

    @Override
    @Transactional
    public Result deleteFolder(Long folderId) {
        Long currentUserId = UserHolder.getUser().getUserId();

        List<FFiles> filesByFolderId = filesMapper.findFilesByFolderId(folderId);
        if (filesByFolderId != null && filesByFolderId.size() > 0) {
            return Result.fail("该文件夹内有文件，删除失败");

        }

        FilesFolder A = folderMapper.selectFolderById(folderId);
        if(A.getFolderPath().equals("") ){
            return Result.fail("根目录无法删除") ;

        }        int affectedRows = folderMapper.deleteFolder(folderId, currentUserId);
        if (affectedRows == 0) {
            throw new RuntimeException("文件夹不存在或无权删除");
        }
        return Result.ok();
    }

    @Override
    @Transactional
    public void updateFolderPath(Long folderId, String newPath) {
        Long currentUserId = UserHolder.getUser().getUserId();
        int affectedRows = folderMapper.updateFolderPath(folderId, currentUserId, newPath);
        if (affectedRows == 0) {
            throw new RuntimeException("文件夹不存在或无权修改");
        }
    }

    @Override
    public FilesFolder getFolderById(Long folderId) {
        FilesFolder folder = folderMapper.selectFolderById(folderId);
        if (folder == null) {
            throw new RuntimeException("文件夹不存在");
        }
        // 权限校验
        if (!folder.getUserId().equals(UserHolder.getUser().getUserId())) {
            throw new RuntimeException("无权访问此文件夹");
        }
        return folder;
    }

    @Override
    public List<FilesFolder> getFoldersByUser() {
        Long currentUserId = UserHolder.getUser().getUserId();
        return folderMapper.selectFoldersByUserId(currentUserId);
    }
    @Override
    public List<FilesFolder> getPathbyuserid(Long userId) {
        //通过用户id查询路径列表

            // 实现逻辑，例如查询数据库
            return folderMapper.findFolderByUserId(userId);
        }

    @Override
    public List<FileTreeNode> searchFolderTreesByKeyword(Long userId, String keyword, boolean includeFiles) {
        // 1. 查询所有匹配关键词的文件夹
        List<FilesFolder> matchedFolders = folderMapper.findFoldersByKeyword(userId, keyword);

        List<FileTreeNode> resultTrees = new ArrayList<>();

        // 2. 为每个匹配的文件夹构建完整的目录树
        for (FilesFolder folder : matchedFolders) {
            FileTreeNode tree = buildFullTreeForFolder(userId, folder, includeFiles);
            resultTrees.add(tree);
        }

        return resultTrees;
    }

    private FileTreeNode buildFullTreeForFolder(Long userId, FilesFolder folder, boolean includeFiles) {
        // 构建当前文件夹节点
        FileTreeNode currentNode = buildFileTreeNodeFromFolder(folder);

        // 递归添加子节点
        addChildrenToNode(userId, currentNode, includeFiles);

        return currentNode;
    }

    private FileTreeNode buildFileTreeNodeFromFolder(FilesFolder folder) {
        String displayPath = folder.getFolderPath();
        boolean isRoot = "".equals(displayPath);
        return new FileTreeNode(
                folder.getFolderId(),
                extractFolderName(displayPath),
                "folder",
                isRoot ? "/" : displayPath
        );
    }

    private void addChildrenToNode(Long userId, FileTreeNode parentNode, boolean includeFiles) {
        String parentPath = parentNode.getPath();
        // 处理根目录的特殊情况
        String queryPath = parentPath.equals("/") ? "" : parentPath;

        // 1. 查询直接子文件夹
        List<FilesFolder> subFolders = folderMapper.selectSubFoldersByPath(queryPath, userId);
        for (FilesFolder subFolder : subFolders) {
            FileTreeNode childNode = buildFileTreeNodeFromFolder(subFolder);
            parentNode.getChildren().add(childNode);
            // 递归处理子文件夹
            addChildrenToNode(userId, childNode, includeFiles);
        }

        // 2. 添加文件（如果需要）
        if (includeFiles) {
            List<FFiles> files = filesMapper.findFilesByFolderId(parentNode.getId());
            for (FFiles file : files) {
                String filePath = parentPath.equals("/") ?
                        parentPath + file.getDisplayName() :
                        parentPath + "/" + file.getDisplayName();

                FileTreeNode fileNode = new FileTreeNode(
                        file.getFilesId(),
                        file.getDisplayName(),
                        "file",
                        filePath,file.getFilesLock()

                );
                fileNode.setSize(file.getFileSize());
                fileNode.setUploadTime(file.getUploadTime());
                fileNode.setFilesLock(file.getFilesLock());
                fileNode.setFileType(file.getFileType());
                parentNode.getChildren().add(fileNode);
            }
        }
    }

    // 从路径中提取最后一级名称
    private String extractFolderName(String path) {
        if (path == null || path.isEmpty()) {
            return "根目录";
        }
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        int lastSlash = path.lastIndexOf('/');
        return lastSlash == -1 ? path : path.substring(lastSlash + 1);
    }


}




